package net_TCP.G;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: qian
 * Date: 2023-02-18
 * Time: 18:12
 */
public class TcpEchoServer {
    //监听端口的socket
    //ServerSocket 就是外场拉客的
    //clientSocket 就是内场服务的
    //ServerSocket 只有一个 ，clientSocket 可以有很多个
    private ServerSocket serverSocket = null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket = new ServerSocket(port);
    }

    public void start() throws IOException {
        System.out.println("服务器启动！");
        while (true){
            Socket clientSocket = serverSocket.accept();
            processConnection(clientSocket);
        }
    }

    //通过这个方法来处理一个连接
    //读取请求
    //根据请求计算响应
    //把响应返回给客户端
    private void processConnection(Socket clientSocket) throws IOException {
        System.out.printf("[%s:%d] 客户端上线\n ",clientSocket.getInetAddress().toString(),
                clientSocket.getPort());
        //try（）这种写法，（）中允许写多个流对象。使用 ；来分割
        try (InputStream inputStream = clientSocket.getInputStream();
             OutputStream outputStream = clientSocket.getOutputStream()){
            //没有这个scanner 和printWriter，完全可以！！但是代价就是得一个字节一个字节扣，找到那个请求的结束笔记\n
            //不是不能做，而是代码比较麻烦
            //为了简单，把字节流包装成了更方便的字符流

            while (true){
                //1.读取请求
                Scanner scanner = new Scanner(inputStream);
                if (!scanner.hasNext()){
                    //读取的流到了结尾了（对端关闭了）
                    System.out.printf("[%s:%d] 客户端下线！",clientSocket.getInetAddress().toString(),
                            clientSocket.getPort());
                    break;
                }
                //直接使用scanner读取一段字符串
                String request = scanner.next();
                //2.根据请求计算响应
                String response = process(request);
                //3.把响应返回给客户端
                PrintWriter printWriter = new PrintWriter(outputStream);
                printWriter.println(response);
                printWriter.flush();

                System.out.printf("[%s: %d] req: %s; resp: %s\n",clientSocket.getInetAddress().toString(),
                        clientSocket.getPort(),request,response);

            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }finally {
            clientSocket.close();
        }
    }

    private String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server=new TcpEchoServer(9090);
        server.start();
    }
}
